"ui";

let ableLogin = true;
let storage = storages.create('config');
let token = storage.get('token') || null;
let cutImgPath = files.getSdcardPath() + "/cut.png"; // files.cwd()
let missionType = 1;


let formData = {
  username: storage.get('username') || '',
  password: storage.get('password') || '',
  dyPageUrl: storage.get('dyPageUrl') || '',
  good: false,
  focus: false,
  forwarding: false,
  play: false
};

let checkboxList = [{ key: 'good', name: '点赞', value: 0 }, { key: 'focus', name: '关注', value: 1 }, { key: 'forwarding', name: '转发' }, { key: 'play', name: '播放' }];

let packagesInfo = {
  dy: 'com.ss.android.ugc.aweme', // 抖音
  zanzan: 'com.zanqzan.app'
};

let feedArr = ['看视频', '同城看直播', '附近人私信'];
let feedStr = feedArr.join('|');
let feedType = 0;
let missionSpeedArr = [{ name: '1-2秒', speed: [1000, 2000] }, { name: '4-5秒', speed: [4000, 5000] }, { name: '5-6秒', speed: [5000, 6000] }];
let missionSpeedActiveIndex = 0;
let httpList = {
  login: 'zcore.zqzan.com/app/account/login',
  getMission: 'http://zcore.zqzan.com/app/douyin/pull/one',
  isSign: 'http://zcore.zqzan.com/app/douyin/my/info',
  upload: 'http://zcore.zqzan.com/app/oss/shot_img',
  sign: 'http://zcore.zqzan.com/app/douyin/do/sign'
};
ui.layout(
  <vertical>
    <appbar>
      <toolbar id="toolbar" bg="#e000ff" title="抖豆助手" />
    </appbar>
    <vertical padding="30px 0">
      <vertical>
        <horizontal>
          <text textSize="14sp" textColor="black" text="攢攢平台账号" /><text textColor="red" text="*" />
          <input id="username" text="{{formData.username}}" w="*" textSize="14sp" />
        </horizontal>

        <horizontal>
          <text textSize="14sp" textColor="black" text="攢攢平台密码" /><text textColor="red" text="*" />
          <input id="password" password="true" text="{{formData.password}}" w="*" textSize="14sp" />
        </horizontal>

        <horizontal>
          <text textSize="14sp" textColor="black" text="抖音主页链接" /><text textColor="red" text="*" />
          <input id="dyPageUrl" text="{{formData.dyPageUrl}}" w="*" textSize="14sp" />
        </horizontal>

        <horizontal>
          <text textSize="14sp" textColor="black" text="注册码" />
          <input id="code" text="" w="*" textSize="14sp" />
        </horizontal>

        <horizontal>
          <checkbox id="good" name="good" text="点赞" />
          <checkbox id="focus" name="focus" text="关注" />
          <checkbox id="forwarding" name="forwarding" text="转发" />
          <checkbox id="play" name="play" text="播放" />
        </horizontal>

        <horizontal>
          <text textSize="14sp" textColor="black" text="养号" />
          <spinner w="*" id="feed" entries="{{feedStr}}" />
        </horizontal>

        <horizontal>
          <text paddingTop="7sp" textSize="14sp" textColor="black" text="任务调速" />
          <radiogroup orientation="horizontal">
            <radio id="speed0" text="{{missionSpeedArr[0].name}}" checked="true" />
            <radio id="speed1" text="{{missionSpeedArr[1].name}}" />
            <radio id="speed2" text="{{missionSpeedArr[2].name}}" />
          </radiogroup>
        </horizontal>

      </vertical>
      <button id="submit" text="确定"></button>
    </vertical>
  </vertical>
);

let init = () => {
  checkboxList.forEach((val, index) => {
    ui[val.key].on("check", (checked) => {
      formData[val.key] = checked;
    });
  });

  missionSpeedArr.forEach((val, index) => {
    ui['speed' + index].on("check", (checked) => {
      if (checked) {
        missionSpeedActiveIndex = index;
      }
    });
  });



  ui.submit.click(() => {
    let feedIndex = tools.getSelectedIndex('feed');
    // console.log(tools.getSpeedTime(missionSpeedArr[missionSpeedActiveIndex].speed))
    if (!ableLogin) {
      return
    }
    if (checkForm()) {
      ableLogin = false;
      let checkArr = [];
      checkboxList.forEach((value, index) => {
        if (formData[value.key]) {
          checkArr.push(value.name)
        }
      });
      if (checkArr.length < 1) {
        toast('请选择任务类型');
        return
      }
      if (!formData.focus) {
        missionType = checkArr[0].value;
      }
      console.log(token && (formData.username == tools.getUiText('username')), 1111111111)
      if (token && (formData.username == tools.getUiText('username'))) {
        isSign(true);
        return
      }
      loginInit();
      // alert('账号:' + tools.getUiText('username') + ', 密码:' + tools.getUiText('password') + ', 主页:' + tools.getUiText('dyPageUrl') + ', 选中:' + checkArr.join())
    }
  });

  let checkForm = () => {
    if (tools.isEmpty(tools.getUiText('username'))) {
      toast('请填写攢攢平台账号');
      return false
    }
    if (tools.isEmpty(tools.getUiText('password'))) {
      toast('请填写攢攢平台密码');
      return false
    }
    if (!tools.checkLink(tools.getUiText('dyPageUrl'))) {
      toast('请填写正确的抖音主页链接');
      return false
    }
    return true
  }
};

let tools = {
  getSpeedTime: (timeArr) => {
    let firstTime = 1000;
    let secondTime = 2000;
    if (timeArr && timeArr[0] && timeArr[1]) {
      firstTime = timeArr[0];
      secondTime = timeArr[1];
    }
    let time = (secondTime - firstTime) * Math.random() + firstTime;
    return time;
  },

  myPost: (url, data, fn, headersParam) => {
    let headers = headersParam || {};
    if (token) {
      headers.headers = { token: token };
    }
    http.post(url, data, headers, (res, err) => {
      if (fn) {
        fn(res, err);
      }
    })
  },

  myGet: (url, data, fn, headersParam) => {
    let headers = headersParam || {};
    if (token) {
      headers.headers = { token: token };
    }
    http.get(url, headers, (res, err) => {
      if (fn) {
        fn(res, err);
      }
    })
  },

  getSelectedIndex: (id) => {
    return ui[id].getSelectedItemPosition();
  },

  getUiText: (id) => {
    return ui[id].getText();
  },

  isEmpty: (value) => {
    let reg = /^\s*$/g;
    return reg.test(value);
  },

  checkLink: (value) => {
    let reg = /^(((https?|ftp|news):\/\/|\w+(\.\w+)+)(:\w+)?).*/;
    return reg.test(value);
  }

};

let loginInit = () => {
  let pwd = String(tools.getUiText('password')) + 'Uk&s23^ruk@';
  pwd = java.math.BigInteger(1, java.security.MessageDigest.getInstance("MD5").digest(java.lang.String(pwd).getBytes())).toString(16);
  let param = {
    "username": tools.getUiText('username'),
    "loginpw": pwd
  };
  tools.myPost(httpList.login, param, function (result, err) {
    if (result.statusCode != 200) {
      sleep(tools.getSpeedTime([3000, 4000]))
      loginInit();
      return
    }
    let res = result.body.json();
    if (res.code != 0) {
      let msg = '登录失败';
      if (res.msg) {
        msg = res.msg;
      }
      toast(msg + '，稍后重新登录');
      return
    }
    let username = tools.getUiText('username') + '';
    let password = tools.getUiText('password') + '';
    let dyPageUrl = tools.getUiText('dyPageUrl') + '';
    storage.put('username', username);
    storage.put('password', password);
    storage.put('dyPageUrl', dyPageUrl);
    toast('登录成功');
    token = res.data.token;
    storage.put('token', token + '');
    isSign();
  })
};

let isSign = (goLogin) => {
  tools.myGet(httpList.isSign, {}, (result, err) => {
    if (result.statusCode != 200) {
      sleep(tools.getSpeedTime([3000, 4000]));
      isSign();
      return
    }
    let res = result.body.json();
    console.log(res)
    if (res.code != 0) {
      if (goLogin) {
        loginInit();
      }
      toast(res.msg);
      return
    }
    if (!res.data.is_signed) {
      ableLogin = true;
      goSign();
      return
    }
    toast('已签到');
    getMission();
  })
};

let goSign = () => {
  let url = tools.getUiText('dyPageUrl') + '';
  tools.myGet(url, {}, (result, err) => {
    if (result.statusCode == 200) {
      let userUrl = result.url + '';
      let userUrlParam = (userUrl.split('user/'))[1] + '';
      let userId = (userUrlParam.split('?'))[0];
      openUserPage(userId);
      return
    }
    sleep(3000);
    goSign();
  })
};

let openUserPage = (userId) => {
  app.startActivity({
    action: "android.intent.action.VIEW",
    data: "snssdk1128://user/profile/" + userId + "?refer=web&gd_label=click_wap_profile_bottom&type=need_follow&needlaunchlog=1"
  });
  sleep(1000);
  if (currentPackage() == packagesInfo.dy) {
    cutImg(true);
    return
  }
  openUserPage(userId);
};

let cutImg = (waitAd) => {
  let ableCutImg = requestScreenCapture(true);
  if (!ableCutImg) {
    alert('请开启截图权限');
    return
  }
  let adTime = parseInt(1000 * Math.random()) + 3000;
  if (files.isFile(cutImgPath)) {
    files.remove(cutImgPath);
    sleep(1000);
  }
  if (waitAd) {
    sleep(adTime);
  }
  if (!ableCutImg) {
    toast('请求截图失败');
    sleep(3000);
    cutImg();
    return
  }
  if (!ableCutImg) {
    toast('请求截图失败');
    sleep(3000);
    cutImg();
    return
  }
  captureScreen(cutImgPath);
  sleep(1000);
  if (files.isFile(cutImgPath)) {
    toastLog('截屏成功');
    signUpload(cutImgPath);
    return
  }
  sleep(1000);
  cutImg();
};

let getUploadParam = (file, fn) => {
  tools.myPost(httpList.upload, {}, (result, err) => {
    if (result.statusCode != 200) {
      sleep(tools.getSpeedTime([3000, 4000]));
      getUploadParam(file, fn);
      return
    }
    let res = result.body.json();
    if (res.code == 0) {
      if (fn) {
        fn(res);
      }
      return
    }
    sleep(tools.getSpeedTime([3000, 4000]));
    getUploadParam(file, fn);
  })
}

let signUpload = (file) => {
  getUploadParam(file, (res) => {
    key = res.data.dir + res.data.prefix + (new Date).getTime() + Math.floor(150 * Math.random()) + ".png"
    let imgPath = res.data.host + "/" + key + res.data.format;
    let param = {
      key: key,
      file: file
    };
    param = Object.assign(param, res.data);
    uploadFn(param, (reponse, err) => {
      if (reponse.statusCode == 200) {
        toast('上传截图成功');
        sign(imgPath);
        return
      }
      toast('上传截图失败');
      sleep(tools.getSpeedTime([3000, 4000]));
      signUpload(file);
    });
  })
  // tools.myPost(httpList.upload, {}, (result, err) => {
  //   console.log(result.statusCode, 111111111111)
  //   if (result.statusCode != 200) {
  //     sleep(tools.getSpeedTime([3000, 4000]));
  //     signUpload(file);
  //     return
  //   }
  //   let res = result.body.json();
  //   if (res.code == 0) {
  //     key = res.data.dir + res.data.prefix + (new Date).getTime() + Math.floor(150 * Math.random()) + ".png"
  //     let imgPath = res.data.host + "/" + key + res.data.format;
  //     let param = {
  //       key: key,
  //       file: file
  //     };
  //     param = Object.assign(param, res.data);
  //     uploadFn(param, (reponse, err) => {
  //       if (reponse.statusCode == 200) {
  //         toast('上传截图成功');
  //         sign(imgPath);
  //         return
  //       }
  //       toast('上传截图失败');
  //     });
  //   }
  // })
};

let uploadFn = (data, fn) => {
  http.postMultipart(data.host, {
    key: data.key,
    policy: data.policy,
    OSSAccessKeyId: data.accessid,
    signature: data.signature,
    success_action_status: '200',
    file: open(data.file)
  }, null, (reponse, err) => {
      if (fn) {
        fn(reponse, err);
      }
  })
};


let sign = (imgPath) => {
  tools.myPost(httpList.sign, { img_url: imgPath }, (result, err) => {
    if (result.statusCode == 200) {
      let res = result.body.json();
      if (res.code != 0) {
        toast('签到失败');
        sleep(3000);
        goSign();
        return
      }
      toast('签到成功');
      getMission();
    }
  })
};

let getMission = () => {
  tools.myPost(httpList.getMission + '?_=' + Date.now(), {
    "b_discount": true,
    "access": missionType,
    "exam_status": 0,
  }, (result, err) => {
      if (result.statusCode != 200) { 
        sleep(tools.getSpeedTime([3000, 4000]));
        getMission();
        return
      }
      let res = result.body.json();
      if (res.data.code == 0) {
        doMission(res.data);
        return
      }
      sleep(tools.getSpeedTime([3000, 4000]));
      getMission();
  })
};

let doMission = (data) => {
  console.log(data)
  switch (data.type) {
    case 1: // 点赞
      goodFn(data);
      break;
  }
};

let goodFn = (data) => {
  console.log(data)
}



init();
